package com.ssy.lingxi.message.websocket.config;

import com.ssy.lingxi.component.redis.service.IRedisUtils;
import com.ssy.lingxi.message.serviceimpl.InSiteMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

import javax.annotation.Resource;

/**
 * webSocket配置
 * @author yzc
 * @version 2.0.0
 * @date 2020/10/27
 */
@Slf4j
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Resource
    private InSiteMessageService inSiteMessageService;
    @Resource
    private IRedisUtils redisUtils;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // 配置处理器
        registry.addHandler(webSocketHandler(), "/message/websocket")
                .addInterceptors(messageWebSocketShakeInterceptor())
                // 解决跨域问题
                .setAllowedOrigins("*");
    }

    @Bean
    public SimpleWebSocketHandler webSocketHandler() {
        return new SimpleWebSocketHandler(inSiteMessageService);
    }

    @Bean
    public SimpleWebSocketShakeInterceptor messageWebSocketShakeInterceptor() {
        return new SimpleWebSocketShakeInterceptor(redisUtils);
    }
}
